<template xmlns:el-col="http://www.w3.org/1999/html">
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px; ">
            <el-form :inline="true" ref="filters" :model="filters" size="small">
                <el-form-item label="高校名称" prop="unit_name">
                    <el-input v-model="filters.unit_name"></el-input>
                </el-form-item>
                <el-form-item label="高校所属" prop="belong">
                    <el-select filterable v-model="filters.belong" clearable　placeholder="请选择高校所属">
                        <el-option :key="item.key" :label="item.value" :value="item.key"
                                   v-for="(item) in dict.univ_department"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="省份" prop="provinces">
                    <el-select filterable v-model="filters.provinces" clearable　placeholder="请选择高校所属省份">
                        <el-option :key="item" :label="item" :value="item"
                                   v-for="(item) in dict.provinces"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="高校类型" prop="arts_type">
                    <el-select filterable v-model="filters.arts_type" clearable　placeholder="请选择高校类型">
                        <el-option :key="item.key" :label="item.value" :value="item.key"
                                   v-for="(item) in dict.univ_pro"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchBtn">搜索</el-button>
                    <el-button @click="resetSearch('filters')">重置</el-button>

                </el-form-item>

                <el-form-item style="display: block; float: right;"  v-if="role_name.indexOf('管理')>-1 || role_name.indexOf('教育部')>-1">
                    <el-button type="primary"  size="medium" @click="handleAdd"><i class="el-icon-plus"></i>新增高校</el-button>
                </el-form-item>
            </el-form>
        </el-col>


        <el-table :data="items" style="width: 100%">
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <el-table-column
                    align="right"  width="80" >
                <template slot-scope="scope">
                    <img v-if="scope.row.unit_logo" style="float:right; width:50px; height:50px;" :src="scope.row.unit_logo.path" class="avatar">
                    <img v-else style="float:right; width:50px; height:50px;" src="/assets/images/icon_university.png" class="avatar">
                </template>
            </el-table-column>
            <el-table-column prop="unit_name" label="高校名称" align="left" />

            <el-table-column prop="belong" label="所属" align="left"  width="200px" >
                <template slot-scope="scope">
                    {{scope.row.belong ? dict.belong[scope.row.belong].value : '--'}} {{scope.row.other_belong ? ' - ' + scope.row.other_belong : ''}}
                </template>
            </el-table-column>
            <el-table-column prop="provinces" label="省份" />
            <el-table-column prop="city" label="城市" />
            <el-table-column prop="arts_type" label="高校类型" align="left"  >
                <template slot-scope="scope">
                    {{scope.row.arts_type ? dict.arts_type[scope.row.arts_type].value : '--'}}
                </template>
            </el-table-column>
            <el-table-column prop="responsible_user_name" label="信息上报人" />
            <el-table-column prop="responsible_user_belong_unit" label="部门"  align="center" />
            <el-table-column prop="responsible_user_title" label="职务" align="center"  />
            <el-table-column label="操作" align="center" width="180" >
                <template slot-scope="scope">
                    <el-button type="primary" plain="" @click="handleDetail(scope.row.id)">详情</el-button>
                    <!--<el-button type="primary" plain="" @click="handleEdit(scope.row)">编辑</el-button>-->
                    <el-button v-if="!is_group" type="danger" plain="" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>


        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <!--分页-->
            <el-pagination
                    style="text-align: center;"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :page-size="pager.page_size"
                    :page-sizes="pager.sizes"
                    background
                    :current-page="pager.page_current"
                    layout="prev,pager,next,sizes,total"
                    :total="pager.total">
            </el-pagination>
        </el-col>

        <el-dialog :title="dialogTitle" v-loading="dialogLoading" :visible.sync="dialogVisible"
                   width="600px" :before-close="handleClose" >
            <el-form :model="itemForm" :rules="itemRules" ref="itemForm" label-width="100px" class="demo-fundProduct">
                <el-row>
                    <el-col :span="20" :push="1">
                        <el-input type="hidden" v-model="itemForm.id"></el-input>
                    </el-col>
                </el-row>

              <!--  <el-row>
                    <el-col :span="8" :push="1">
                        <el-form-item label="高校logo:">
                            <span>
                                &lt;!&ndash;<img v-if="itemForm.unit_logo.id == null " class="am-avatar" :src="'/common/images/' + imgUrl" @click="fileSelect()" />&ndash;&gt;
                                <img v-if="imgUrl" class="am-avatar" :src="imgUrl" @click="fileSelect()" />
                            </span>
                            <div class="am-avatar-uploader am-avatar-uploader-icon" :style="imgUrl?'display:none;': '' ">
                                <i class="el-icon-plus"></i>
                                <input type="file" name="fileToUpload" id="fileToUpload" @change="fileSelected()" />
                            </div>
                        </el-form-item>

                    </el-col>
                </el-row>-->

                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="高校logo:">
                            <el-upload
                                    class="avatar-uploader"
                                    action="/common/upload"
                                    :show-file-list="false"
                                    :on-success="handleAvatarSuccess"
                                    :before-upload="beforeAvatarUpload">
                                <img v-if="imageUrl" :src="imageUrl" class="avatar">

                                <i v-else   class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                            <span style="font-size:12px;margin-top:-20px;" >点击上传标志</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="高校名称:" prop="unit_name">
                            <el-input placeholder="请输入高校名称" type="text" v-model="itemForm.unit_name"></el-input>
                        </el-form-item>
                        <el-form-item label="所在省市:" prop="provinces" style="width:260px">
                            <el-cascader
                                    　placeholder="请选择所在省市"
                                    v-model="selecetProvincCity"
                                    :options="dict.provinc_city"
                                    :props="provincCityProps"
                                    @change="provincCityChange"></el-cascader>
                            </el-select>
                           <!-- <el-select filterable v-model="itemForm.provinces" clearable　placeholder="请选择高校所属省份">
                                <el-option :key="item" :label="item" :value="item"
                                           v-for="(item) in dict.provinces"></el-option>
                            </el-select>-->
                        </el-form-item>
                        <el-form-item label="高校所属:" prop="belong" style="width:260px">
                            <el-select filterable v-model="itemForm.belong" clearable　placeholder="请选择高校所属">
                                <el-option :key="item.key" :label="item.value" :value="item.key"
                                           v-for="(item) in dict.univ_department"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="部委名称"  prop="other_belong" v-if="itemForm.belong == 4">
                            <el-input v-model="itemForm.other_belong" placeholder="请输入其他部委名称"></el-input>
                        </el-form-item>
                        <el-form-item label="高校类型:" prop="arts_type" style="width:260px">
                            <el-select filterable v-model="itemForm.arts_type" clearable　placeholder="请选择高校类型">
                                <el-option :key="item.key" :label="item.value" :value="item.key"
                                           v-for="(item) in dict.univ_pro"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!--<el-row>
                    <el-col :span="20" :push="1">
                        <el-form-item label="添加日期:">
                            <span>{{itemForm.create_date}}</span>
                        </el-form-item>
                    </el-col>
                </el-row>-->


            </el-form>

            <div slot="footer" class="dialog-footer">

                    <el-button type="primary" @click="submit">保 存
                    </el-button>
                    <el-button @click="handleClose">取 消</el-button>

            </div>

        </el-dialog>

        <!--对话框-显示大图-->
        <el-dialog title="显示大图" :visible.sync="big_img_dialog.show">
            <img class="big-img" :src="big_img_dialog.path">
        </el-dialog>


    </section>


</template>

<script>
    import * as api from '../../api/auth_api.js';
    import {update_img} from "../../api/common";
    import {userName, password} from "../../common/js/checkFields";
    import {formatDate} from "../../common/js/date";
    import {isNullTrue} from "../../common/js/commons";
    import dict  from '../../common/js/dict'

    export default {
        computed:{
            role_name(){
                let role_name =this.$store.state.userInfo.role_name || ''
                return role_name
            }
        },
        data() {
            var validName = (rule, value, callback) => {
                // let reg = /^[a-zA-Z\u4e00-\u9fa5]{1,30}$/;
                // 高校名称只验证长度 30
                if (value.length > 30) {
                    callback(new Error('30位以内的汉字或字母'));
                } else if(value == '') {
                    callback(new Error('请输入高校名称'));
                } else {
                    callback();
                }
            };
            return {
                dict: dict,
                is_group:false,
                big_img_dialog: {
                    show: false,
                    path: ''
                },
                //分页设置
                pager: {
                    sizes: [10, 20, 30, 40, 50],
                    total: 0,
                    page_size: 10,
                    page_current: 1
                },
                items: [],
                selecetProvincCity:[],
                provincCityProps:{
                    value:'name',
                    label:'name',
                    children:'city'
                },
                filters: {
                    unit_name: '',
                    provinces: '',
                    arts_type: '',
                    belong: ''
                }

                //dialog
                ,dialogVisible: false
                ,dialogLoading: false
                ,dialogTitle: '创建高校'
                ,itemForm: {
                    id: '',
                    unit_name: "",
                    provinces: "",
                    city: "",
                    belong:"",
                    other_belong:"",
                    arts_type:"",
                    // create_date: formatDate(new Date(),'yyyy-MM-dd hh:mm:ss'),  //日期格式化
                }
                ,is_itemForm: false     //判断是新增还是编辑，默认新增
                ,unit_logo: {}
                ,itemRules: {
                    unit_name: [{required: true, message: '请输入高校名称',validator: validName, trigger: 'blur'}],
                    provinces:{required: true, message: '请选择高校所属省份' , trigger: 'change'},
                    other_belong:{required: true, message: '请输入其他部委名称' , trigger: 'blur'},
                    belong:{required: true, message: '请选择高校所属部署' , trigger: 'change'},
                    arts_type:{required: true, message: '请选择高校所属类型' , trigger: 'change'}
                }

                //上传logo地址
                // ,imgList: []
                ,imgUrl: ''
                ,temp_imgUrl: ''
                ,imageUrl: ''
            }
        },
        methods: {
            handleDetail(id){
              this.$router.push({name:'高校详情',params:{id:id}})
            },
            //分页page_size发生改变
            handleSizeChange(val) {
                this.pager.page_current = 1;
                this.pager.page_size = val;
                this.getItems();
            },
            //分页page_current发生改变
            handleCurrentChange(val) {
                this.pager.page_current = val;
                this.getItems();
            },
            getItems() {
                // let condition = {};
                let params = {
                    condition: this.filters,
                    page_size: this.pager.page_size,
                    page_current: this.pager.page_current
                };
                if (this.role_name.indexOf("专家")>-1){
                    params.leader = true
                    this.is_group = true
                }else{
                    params.leader = false
                    this.is_group = false
                }
                api.universityList(params).then((res) => {
                    if (res.data.status === 200) {
                        let datas = JSON.parse(res.data.datas);
                        this.items = datas.items;
                        this.pager.total = datas.total;
                    } else {
                        this.$message.error(res.data.status + " " + res.data.msg);
                    }

                });
            },

            searchBtn() {
                this.pager.page_current = 1;
                this.getItems();
            },
            resetSearch(formName) {
                this.$refs[formName].resetFields();
                this.searchBtn();
            },

            // ========================================= logo - upload start ===============================================
            fileSelect(){
                document.getElementById("fileToUpload").click();
            },
            fileSelected(){
                var item = document.getElementById("fileToUpload").files[0];
                //判断格式是否正确
                var flag = this.beforeAvatarUpload(item);
                // 文件选择后触发次函数 上传
                if(flag) {
                    this.httpRequestImg(item);
                }
            },
            //上传后台
            httpRequestImg(item) {
                let formData = new FormData();
                formData.append('file', item);
                update_img(formData).then((res) => {
                    let result = JSON.parse(res.data.datas);
                    if (res.data.status == 200) {

                        this.unit_logo = {
                            id: result.id
                        };
                        this.imgUrl = this.temp_imgUrl;

                    } else {
                        if (res.data.status === 401) {
                            this.$router.push('/login');
                        }
                        this.$message.error(res.data.msg);
                        // this.imgList = [];
                    }
                });
            },

            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);

               /* this.formUnit.unit_logo= {
                    id: JSON.parse(res.datas).id
                }*/
                this.itemForm.unit_logo = {
                    id: JSON.parse(res.datas).id
                }


            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    // this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isLt2M;
            },


            // handleAvatarSuccess(res, file) {
            //     this.imgList = [{'name': file.name, 'url': URL.createObjectURL(file.raw)}];
            // },
            // httpRequest(item,fileList) {
            //     let formData = new FormData();
            //     formData.append('file', item.file);
            //     update_img(formData).then((res) => {
            //         let result = JSON.parse(res.data.datas);
            //         if (res.data.status == 200) {
            //
            //             get_update_img({id: result.id}).then((res) => {
            //                 if (res.data.status == 200) {
            //                     this.imgUrl = res.data.datas;
            //                     this.unit_logo = {
            //                         id: result.id,
            //                         path: res.data.datas
            //                     };
            //                 }
            //             });
            //
            //
            //         } else {
            //             if (res.data.status === 401) {
            //                 this.$router.push('/login');
            //             }
            //             this.$message.error(res.data.msg);
            //             this.imgList = [];
            //         }
            //     });
            // },
            beforeAvatarUpload(file) {
                const extension2 = file.type.toLowerCase() === 'image/jpeg';
                const extension3 = file.type.toLowerCase() === 'image/png';
                const extension = file.type.toLowerCase()  === 'jpg';
                // const extension4 =  file.type.toLowerCase() === 'bmp';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!extension && !extension2 && !extension3) {
                    this.$message({
                        message: '上传图片只能是.jpg、.png、.jpeg格式!',
                        type: 'warning'
                    });
                }

                if (!isLt2M) {
                    this.$message({
                        message: '上传图片大小不能超过 2MB!',
                        type: 'warning'
                    });
                }
                if(window.createObjectURL != undefined) {
                    this.temp_imgUrl = window.createObjectURL(file);
                }else if(window.URL != undefined) {
                    this.temp_imgUrl = window.URL.createObjectURL(file);
                } else if(window.webkitURL != undefined) {
                    this.temp_imgUrl = window.webkitURL.createObjectURL(file);
                }
                return (extension || extension2 || extension3 ) && isLt2M;
            },
            // handleExceed(files, fileList) {
            //     this.$message.warning(`限制只能上传1个文件`);
            // },


            // ========================================= logo - upload end ===============================================
            // ========================================= add start ===============================================
            handleAdd() {
                this.dialogTitle = '创建高校';
                this.dialogVisible = true;
                this.is_itemForm = false;
                this.$nextTick(()=>{
                    this.$refs['itemForm'].clearValidate();
                })
            },
            submit() {
                this.$refs['itemForm'].validate((valid) => {
                    if (valid) {
                        var condition = {
                            unit_name: this.itemForm.unit_name,
                            unit_logo: this.itemForm.unit_logo,
                            provinces:this.itemForm.provinces,
                            city:this.itemForm.city,
                            other_belong:this.itemForm.other_belong,
                            belong:this.itemForm.belong,
                            arts_type:this.itemForm.arts_type
                        };
                        this.dialogLoading = true;  //显示loading
                        if(!this.is_itemForm){
                            api.addUniversity(condition).then((res) => {
                                this.dialogLoading = false;  //隐藏loading
                                if (res.data.status == 200) {
                                    this.$message({
                                        type: 'success',
                                        message: '添加成功!'
                                    });
                                    this.handleClose();
                                    this.dialogVisible = false;

                                    this.getItems();
                                } else {
                                    if (res.data.status == 401) {
                                        this.$router.push('/login');
                                    }
                                    this.$message.error(res.data.msg);
                                    this.dialogVisible = false;

                                    this.handleClose();
                                }
                            });
                        }else{
                            condition.id = this.itemForm.id;
                            api.updateUniversity(condition).then((res) => {
                                this.dialogLoading = false;  //隐藏loading
                                if (res.data.status == 200) {
                                    this.$message({
                                        type: 'success',
                                        message: '编辑成功!'
                                    });
                                    this.handleClose();
                                    this.dialogVisible = false;

                                    this.getItems();
                                } else {
                                    if (res.data.status == 401) {
                                        this.$router.push('/login');
                                    }
                                    this.$message.error(res.data.msg);
                                    this.dialogVisible = false;

                                    this.handleClose();
                                }
                            });
                        }
                    }
                });
            },
            handleClose() {
                this.unit_logo = {};
                this.selecetProvincCity = [];
                this.itemForm = {
                        id: '',
                        unit_name: "",
                        provinces: "",
                        city: "",
                        belong:"",
                        other_belong:"",
                        arts_type:"",
                };
                // this.imgList = [];
                this.imgUrl = '';
                this.$nextTick(()=>{
                    this.dialogVisible = false;
                })
            },
            // ========================================= add end ===============================================
            // ========================================= edit start ===============================================
            handleEdit(row) {
                this.dialogTitle = '编辑高校';
                this.dialogVisible = true;
                this.is_itemForm = true;
                this.dialogLoading = true;  //显示loading
                let params = {"id": row.id};
                api.universityInfo(params).then((res) => {
                    if (res.data.status === 200) {
                        this.dialogLoading = false;  //显示loading
                        this.itemForm = JSON.parse(res.data.datas);
                        if(!isNullTrue(this.itemForm.unit_logo)){
                            // this.imgList = [{name: this.itemForm.unit_name, url: this.itemForm.unit_logo.path}];
                            this.imgUrl = this.itemForm.unit_logo.path;
                            this.unit_logo = {
                                id: this.itemForm.unit_logo.id
                                // path: this.itemForm.unit_logo.path
                            };
                        }
                    } else {
                        this.$message({
                            type: 'info',
                            message: '系统繁忙'
                        });
                    }
                });
            },
            // ========================================= edit end ===============================================

            handleDelete(row) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let params = {"id": row.id};
                    api.removeUniversity(params).then((res) => {
                        if (res.data.status === 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getItems();
                        } else {
                            this.$message({
                                type: 'info',
                                message: result.msg
                            });
                        }
                    });

                });
            },

            showBigImg(path) {
                this.big_img_dialog = {
                    show: true,
                    path: path
                }
            },
            provincCityChange(val){
                this.itemForm.provinces = val[0]
                this.itemForm.city = val[1]
            },

        },
        mounted() {
            this.$nextTick(function () {

                this.getItems();
            })
        }

    }
</script>
<style>
    .dialog-footer {
        padding-top: 50px;
        text-align: center;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 80px;
        height: 80px;
        line-height: 80px;
        text-align: center;
    }
    .avatar {
        width: 80px;
        height: 80px;
        display: block;
    }
    .disabled .el-upload--picture-card {
        display: none;
    }

    /*========================================upload img =============================================*/
    .am-avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 80px;
        height: 80px;
        line-height: 80px;
        text-align: center;

        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        /*position: absolute;*/
        position: relative;
        overflow: hidden;
    }
    .am-avatar-uploader input[type=file]
    {
        position:absolute;
        top: 0;
        left: 0;
        z-index:1;
        width:100%;
        height: 100%;
        font-size:50rem;
        opacity:0;
        filter: alpha(opacity=0);
        cursor:pointer;
    }


    .am-avatar {
        width: 80px;
        height: 80px;
        display: inline-block;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
    }
</style>
